'use strict';

const Controller = require('../core/base_controller');

class Database extends Controller {

	async databases () {
		const result = await this.ctx.service.database.databases();
		this.success(result);
	}

	async tables() {
		const { ctx } = this;
		const { db } = ctx.request.body;

		const result = await ctx.service.database.tables(db);
		this.success(result);
	}


	async cols() {
		const { app, ctx } = this;

		const { tablename, multiple, db } = ctx.request.body;

		const result = await ctx.service.database.cols(tablename, multiple, db);
		
		this.success(result);
	}



	async createApi () {

		const { app, ctx } = this;

		const { name, sql, id } = ctx.request.body;

		const result = await this.ctx.service.database.createApi({
			id,
			name,
			json : sql,
		});


		const result1 = await this.ctx.service.database.getApi(name)
		
		this.success(result1);

	}


	async getApi () {
		const { app, ctx } = this;

		const { name } = ctx.request.query;

		let sqlinfo = await app.redis.get('system').hget('dlq_sql', name);

		console.log('sqlinfo');
		console.log(sqlinfo);

		if(sqlinfo == null){
			sqlinfo = await this.ctx.service.database.getApi(name);
		}

		sqlinfo = JSON.parse(sqlinfo);
		this.success(sqlinfo);
	}


	async delApi () {
		const { app, ctx } = this;

		const { id, name } = ctx.request.query;

		const result = await this.ctx.service.database.createApi({
			id,
			del_flag : '1',
		});

		const delresult = await app.redis.get('system').hdel('dlq_sql', name);

		console.log(result);
		console.log(delresult);

		this.success(result);
	}
}

module.exports = Database;
